package com.gitee.cui.security.netty.securechat;

import com.gitee.cui.config.SystemConfig;
import com.gitee.cui.ssl.SSLContextHelper;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslHandler;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;

/**
 * Netty版安全聊天服务端
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/5 15:55
 **/
public class SecureChatServer {

    public static void startServer() {
        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            bootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(SystemConfig.SOCKET_SERVER_PORT)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .childHandler(new SecureChatInitializer());

            ChannelFuture future = bootstrap.bind().sync();

            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }

    private static class SecureChatInitializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            SSLContext context = SSLContextHelper.createServerSSLContext();
            SSLEngine engine = context.createSSLEngine();
            engine.setUseClientMode(false);
            engine.setNeedClientAuth(false);
            SslHandler sslHandler = new SslHandler(engine);
            // 添加SslHandler处理器，处理加密内容
            pipeline.addLast(sslHandler);
            // 添加分包器
            pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
            // 添加字符串解码器
            pipeline.addLast("decoder", new StringDecoder());
            // 添加字符串编码器
            pipeline.addLast("encoder", new StringEncoder());
            // 添加聊天处理器
            pipeline.addLast("handler", new ServerChatHandler());
        }
    }
}
